<?php
namespace app\models;

use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\rbac\DbManager;
use yii\rbac\Item;

/**
 * RBAC权限操作
 * Class RbacManager
 * @package app\models
 */
class RbacManager extends DbManager
{
    /**
     * 返回所有顶级权限
     * @return array
     */
    public static function getTopAuthItems()
    {
        $authManager = new parent();
        $all = (new Query)
            ->from($authManager->itemTable)
            ->where(['type'=> Item::TYPE_PERMISSION])
            ->all();
        $child = (new Query)
            ->from($authManager->itemChildTable)
            ->where(['parent'=>ArrayHelper::getColumn($all, 'name')])
            ->all();
        $child = ArrayHelper::getColumn($child, 'child');
        $items = [];
        foreach ($all as $item) {
            if (in_array($item['name'], $child)) {
                continue;
            }
            $items[] = $item;
        }
        return $items;
    }

    /**
     * 返回权限列表
     * @param string $parent=null 限制上级
     * @return array
     */
    public static function getAuthItems($parent = null)
    {
        if (empty($parent)) {
            return RbacManager::getTopAuthItems();
        }
        $authManager = new parent();
        $child = (new Query())
            ->from($authManager->itemChildTable)
            ->where(['parent'=>$parent])
            ->all();
        $child = ArrayHelper::getColumn($child, 'child');
        $items = (new Query())
            ->from($authManager->itemTable)
            ->where(['name'=>$child])
            ->all();
        return $items;
    }

    /**
     * 根据名称返回权限信息
     * @param string $item_name
     * @return null|Item
     */
    public static function getAuthItem($item_name)
    {
        $authManager = new parent();
        return $authManager->getItem($item_name);
    }

    /**
     * 根据名称返回角色信息
     * @param string $role_name
     * @return null|\yii\rbac\Role
     */
    public static function getAuthRole($role_name)
    {
        $authManager = new parent();
        return $authManager->getRole($role_name);
    }

    /**
     * 删除权限（主要用来删除角色）
     * @param string $item_name
     * @return boolean
     */
    public static function removeAuthItem($item_name)
    {
        $authManager = new parent();
        $item = $authManager->getItem($item_name);
        if (empty($item)) {
            return false;
        }
        return $authManager->removeItem($item);
    }
}
